//
//  AppDelegate.m
//  DingDongZP
//
//  Created by Jyh on 16/3/9.
//  Copyright © 2016年 iyhjiang.com. All rights reserved.
//

#import "AppDelegate.h"
#import "DDAppDelegateResource.h"
#import "DDCheckUpdata.h"

@interface AppDelegate ()
@property (nonatomic, strong) DDAppDelegateResource *delegateResource;//代理模型

@end

@implementation AppDelegate

//app lanuch
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    
    
    
    [self setupLaunch:application andLaunchOptions:launchOptions];
    [self setNoti];
    [self.window makeKeyAndVisible];
    return YES;
}


#pragma mark - 推送消息处理
/** 推送配置 */
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings: (UIUserNotificationSettings *)notificationSettings {
    
    [application registerForRemoteNotifications];
}

/** 推送处理 */
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
    //    NSLog(@"---  获取到的设备DeviceToken   %@",token);
    
    //注册融云
    [[RCIMClient sharedRCIMClient] setDeviceToken:token];
    //注册个推
    [GeTuiSdk registerDeviceToken:token];
    
}
//位于前台
- (void)applicationDidBecomeActive:(UIApplication *)application {
    
//    //是否执行更新jspatch
//    [NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost/JSPatch/main.js"]] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//        NSString *script = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//        DDLog(@"%@",script);
//        
//        [JPEngine evaluateScript:script];
//    }];
//    
    
    [[UIApplication sharedApplication]setApplicationIconBadgeNumber:0];
    
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    // userInfo为远程推送的内容
    //    NSLog(@"---  didReceiveRemoteNotification 推送内容  %@",userInfo);
}

#pragma mark - Handle URL

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    
    return [WXApi handleOpenURL:url delegate:_delegateResource] || [WeiboSDK handleOpenURL:url delegate:_delegateResource];
}


- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    
    return [WXApi handleOpenURL:url delegate:_delegateResource] || [WeiboSDK handleOpenURL:url delegate:_delegateResource];
}


#pragma mark - Private Method

-(void) setupLaunch:(UIApplication *)application andLaunchOptions:(NSDictionary *)launchOptions {
    
    /** sdk相关初始化 */
    _delegateResource = [[DDAppDelegateResource alloc] init];
    //注册推送, 用于iOS8以及iOS8之后的系统
    UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert)
                                                                             categories:nil];
    [application registerUserNotificationSettings:settings];
    [application setApplicationIconBadgeNumber:0];
    
    // 远程推送的内容
    //    NSDictionary *remoteNotificationUserInfo = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey];
    //    NSLog(@"-- 远程推送内容    %@",remoteNotificationUserInfo);
    // 程序第一次启动(包括升级)
    if ([DDLoginUserManager isFirstLaunch]) {
        
        [DDAppDelegateResource showNewIntro];
        
    } else {
        // 登录状态
        [self startLoginProgress];
    }
    
    // 是否由通知 开启app
    if (launchOptions != nil && [DDLoginUserManager isLogin]) {
        
        RDVTabBarController *rootvc = (LDMainTabBarVC *)self.window.rootViewController;
        rootvc.selectedIndex = 2;
    }
}

//执行登录逻辑
- (void) startLoginProgress {
    
    /**  检查是否有版本更新 */
    DDCheckUpdata *checkManager = [DDCheckUpdata shareManager];
    [checkManager checkUpdata];
    
    WEAKSELF
    // 登录状态
    if ([DDLoginUserManager isLogin]) {
        
        if ([DDClientInfoManager clientType] == DDClientTypeBoss) {
            
            [weakSelf initBossTabbarController];
            [self.delegateResource cacheBossInfo];
        } else {
            
            [weakSelf initCattleTabbarController];
            [self.delegateResource cacheUserinfo];
        }
        
    } else {
        
        // 未登录状态
        [weakSelf setNoLoginRecVC];
    }
}

- (void) setNoti {
    
    //监听宣传页面
    WEAKSELF
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:NOTI_GUIDERIMGVIEW_END object:nil] subscribeNext:^(id x) {
        
        [weakSelf startLoginProgress];
    }];
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

//未注册展示页面
- (void)setNoLoginRecVC
{
    DDWelcomeViewController *recVC = [[DDWelcomeViewController alloc] init];
    LDRootNavVC *rootNav = [[LDRootNavVC alloc] initWithRootViewController:recVC];
    
    self.window.rootViewController = rootNav;
}

- (void)initCattleTabbarController {
    
    [DDClientInfoManager initClientType:DDClientTypeCattle];
    [[DDLoginManager sharedManager] loginRongyun:nil failure:nil];
    
    LDMainTabBarVC *vc = [[LDMainTabBarVC alloc] init];
    vc.clientType = DDClientTypeCattle;
    self.window.rootViewController = vc;
}

- (void)initBossTabbarController {
    
    [DDClientInfoManager initClientType:DDClientTypeBoss];
    [[DDLoginManager sharedManager] loginRongyun:nil failure:nil];
    
    
    LDMainTabBarVC *vc = [[LDMainTabBarVC alloc] init];
    vc.clientType = DDClientTypeBoss;
    
    self.window.rootViewController = vc;
}

@end
